package com.talent.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.util.FileCopyUtils;

/**
 * @author watson
 * @Description"
 * @date: 2025/2/14 19:42
 */
@Configuration
@EnableResourceServer
@Slf4j
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    /**
     * 设置公钥
     */
    
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(jwtTokenStore());
    }

    private TokenStore jwtTokenStore() {

        JwtTokenStore jwtTokenStore = new JwtTokenStore(accessTokenConverter());
        return jwtTokenStore;
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        //resource 验证token 公钥

        ClassPathResource classPathResource = new ClassPathResource("pub.pem");

        try {
            byte[] bytes = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
            JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
            String pubKey = new String(bytes);
         //   pubKey = pubKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "").trim();
           // pubKey = "-----BEGIN PUBLIC KEY-----\n" + pubKey + "\n-----END PUBLIC KEY-----";
            log.info("公钥是【{}】", pubKey);
            jwtAccessTokenConverter.setVerifierKey(pubKey);

            return jwtAccessTokenConverter;
        } catch (Exception e) {
            e.printStackTrace();
        }

        log.info("=====");
        return null;
    }


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .sessionManagement().disable()
                .authorizeRequests()
                .antMatchers("/login","/demo","/userId/1","/actuator/env").permitAll()
                .anyRequest().authenticated()
                .and()
                .headers()
                .cacheControl();
    }
}
